package com.example.comiccenter.service.implt;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.comiccenter.dao.ChapterMapper;
import com.example.comiccenter.dao.ComicMapper;
import com.example.comiccenter.dao.PageMapper;
import com.example.comiccenter.domain.Chapter;
import com.example.comiccenter.domain.Comic;
import com.example.comiccenter.domain.ComicPage;
import com.example.comiccenter.service.ComicPageService;
import com.example.comiccenter.utils.ResultData;
import com.example.comiccenter.utils.SearchBean;
import org.apache.commons.io.FileUtils;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

import static com.example.comiccenter.utils.Consts.rootPath;
import static com.example.comiccenter.utils.Consts.targetRootPath;

@Service
public class ComicPageServiceImpl implements ComicPageService {
    @Resource
    private ChapterMapper chapterMapper;
    @Resource
    private PageMapper pageMapper;
    @Resource
    private ComicMapper comicMapper;

    @Override
    public ResultData getAllPage(SearchBean<ComicPage> searchBean) {
        QueryWrapper<ComicPage> wrapper = new QueryWrapper<>();
        wrapper.eq("comicName",searchBean.getData().getComicName())
                .eq("chapterNumber",searchBean.getData().getChapterNumber())
                .eq(searchBean.getData().getPageNumber()!=null,"pageNumber",searchBean.getData().getPageNumber());
        Page<ComicPage> comicPages = pageMapper.selectPage(new Page<>(searchBean.getPageNum(), searchBean.getPageSize()), wrapper);
        return ResultData.success("查询成功",comicPages.getRecords());
    }


    //默认增加在本章节的最后一页
    //增加记录，转存文件
    //更新作品和章节中的页数
    @Override
    public ResultData addPage(ComicPage comicPage, MultipartFile pageFile) {
        if (pageFile == null || pageFile.isEmpty()){
            return ResultData.error(400,"请上传图片");
        }
        //查询本章节中已有页码
        QueryWrapper<Chapter> wrapper = new QueryWrapper<>();
        wrapper.eq("comicName",comicPage.getComicName()).eq("chapterNumber",comicPage.getChapterNumber());
        Chapter chapter = chapterMapper.selectOne(wrapper);
        comicPage.setPageNumber(chapter.getPageNumber()+1);

        String path = rootPath + "\\comic\\" + comicPage.getComicName() + "\\chapter_" + comicPage.getChapterNumber() + "\\";
        String targetPath = targetRootPath + "\\comic\\" + comicPage.getComicName() + "\\chapter_" + comicPage.getChapterNumber() + "\\";
        String fileName = comicPage.getPageNumber() + ".jpg";
        String filePath = path + fileName;
        String targetFilePath = targetPath + fileName;
        String pagePath = "\\images\\comic\\" + comicPage.getComicName() + "\\chapter_" + comicPage.getChapterNumber() + "\\" + fileName;
        File file = new File(filePath);
        File file2 = new File(targetFilePath);
        try {
            FileUtils.copyInputStreamToFile(pageFile.getInputStream(), file);
            FileUtils.copyInputStreamToFile(pageFile.getInputStream(), file2);
            comicPage.setPageStorage(pagePath);

            pageMapper.insert(comicPage);

            //修改本章节中的页数
            chapter.setPageNumber(chapter.getPageNumber()+1);
            chapterMapper.updateById(chapter);

            //修改作品的页数
            QueryWrapper<Comic> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("name",comicPage.getComicName());
            Comic comic = comicMapper.selectOne(wrapper2);
            comic.setPages(comic.getPages()+1);
            comicMapper.updateById(comic);

            return ResultData.success("添加成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    //如果没传入要删除的页码，则默认删除最后一页
    //删除完成后删除对应文件以及更新章节和作品中的页数
    @Override
    public ResultData deletePage(ComicPage comicPage) {
        QueryWrapper<Chapter> wrapper = new QueryWrapper<>();
        wrapper
                .eq("comicName",comicPage.getComicName())
                .eq("chapterNumber",comicPage.getChapterNumber());
        Chapter chapter = chapterMapper.selectOne(wrapper);
        if (comicPage.getPageNumber() == null){

            comicPage.setPageNumber(chapter.getPageNumber());
        }
        QueryWrapper<ComicPage> pageQueryWrapper = new QueryWrapper<>();
        pageQueryWrapper.eq("comicName",comicPage.getComicName()).eq("chapterNumber",comicPage.getChapterNumber()).eq("pageNumber",comicPage.getPageNumber());
        pageMapper.delete(pageQueryWrapper);
        String pageFilePath = rootPath + "\\comic\\" + comicPage.getComicName() + "\\chapter_" + comicPage.getChapterNumber() + "\\" + comicPage.getPageNumber() + ".jpg";
        String targetpageFilePath = targetRootPath + "\\comic\\" + comicPage.getComicName() + "\\chapter_" + comicPage.getChapterNumber() + "\\" + comicPage.getPageNumber() + ".jpg";
        File pageFile = new File(pageFilePath);
        File targetpageFile = new File(targetpageFilePath);
        if (pageFile.exists()) {
            pageFile.delete();
        }
        if (targetpageFile.exists()){
            targetpageFile.delete();
        }

        //修改本章节中的页数
        chapter.setPageNumber(chapter.getPageNumber()-1);
        chapterMapper.updateById(chapter);

        //修改作品的页数
        QueryWrapper<Comic> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("name",comicPage.getComicName());
        Comic comic = comicMapper.selectOne(wrapper2);
        comic.setPages(comic.getPages()-1);
        comicMapper.updateById(comic);

        return ResultData.success("删除成功");
    }

    //废弃
    @Override
    public ResultData updatePage(ComicPage comicPage, MultipartFile pageFile) {
        if (pageFile != null){
            String originalFilename = pageFile.getOriginalFilename();
            System.out.println(originalFilename);
            String suffix = originalFilename.split("\\.")[1];
            if (!"jpg".equals(suffix)){
                return ResultData.error(401,"文件格式错误,请上传jpg文件");
            }else {
                //获取漫画名用于给封面命名
                String path = rootPath + "\\comic\\" + comicPage.getComicName() + "\\chapter_" + comicPage.getChapterNumber() + "\\";
                String targetPath = targetRootPath + "\\comic\\" + comicPage.getComicName() + "\\chapter_" + comicPage.getChapterNumber() + "\\";
                String fileName = comicPage.getPageNumber() + ".jpg";
                String filePath = path + fileName;
                String targetFilePath = targetPath + fileName;
                String pagePath = "\\images\\comic" + comicPage.getComicName() + "\\chapter_" + comicPage.getChapterNumber() + "\\ " + fileName;
                File file = new File(filePath);
                File file2 = new File(targetFilePath);
                try {
//                    pageFile.transferTo(file);
//                    pageFile.transferTo(file2);
                    FileUtils.copyInputStreamToFile(pageFile.getInputStream(), file);
                    FileUtils.copyInputStreamToFile(pageFile.getInputStream(), file2);
                    comicPage.setPageStorage(pagePath);
                    return ResultData.success("修改成功");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        pageMapper.updateById(comicPage);
        return ResultData.success("修改成功");
    }
}
